package com.gy.assistant.ui.chat.group;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMConversationNotificationStatusSetCallback;
import im.zego.zim.callback.ZIMGroupAttributesQueriedCallback;
import im.zego.zim.callback.ZIMGroupAvatarUrlUpdatedCallback;
import im.zego.zim.callback.ZIMGroupDismissedCallback;
import im.zego.zim.callback.ZIMGroupInfoQueriedCallback;
import im.zego.zim.callback.ZIMGroupLeftCallback;
import im.zego.zim.callback.ZIMGroupMemberCountQueriedCallback;
import im.zego.zim.callback.ZIMGroupMemberInfoQueriedCallback;
import im.zego.zim.callback.ZIMGroupMemberListQueriedCallback;
import im.zego.zim.callback.ZIMMessageDeletedCallback;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMGroupAttributesUpdateInfo;
import im.zego.zim.entity.ZIMGroupFullInfo;
import im.zego.zim.entity.ZIMGroupInfo;
import im.zego.zim.entity.ZIMGroupMemberInfo;
import im.zego.zim.entity.ZIMGroupMemberQueryConfig;
import im.zego.zim.entity.ZIMGroupOperatedInfo;
import im.zego.zim.entity.ZIMMessageDeleteConfig;
import im.zego.zim.enums.ZIMConversationNotificationStatus;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMErrorCode;
import im.zego.zim.enums.ZIMGroupAttributesUpdateAction;
import im.zego.zim.enums.ZIMGroupMemberEvent;
import im.zego.zim.enums.ZIMGroupMemberState;
import im.zego.zim.enums.ZIMGroupMessageNotificationStatus;
import com.gy.assistant.R;
import com.gy.assistant.SDKManager;
import com.gy.assistant.enums.MessageLoadType;
import com.gy.assistant.ui.BaseActivity;
import com.gy.assistant.ui.chat.group.adapter.GroupMemberGridAdapter;
import com.gy.assistant.enums.GroupRoleType;
import com.gy.assistant.ui.MainActivity;
import com.gy.assistant.util.AppLogger;
import com.gy.assistant.util.GlideUtils;

public class ZIMGroupInfoDetailActivity extends BaseActivity implements ZIMGroupMemberListQueriedCallback, ZIMGroupInfoQueriedCallback, ZIMGroupAttributesQueriedCallback, ZIMGroupMemberCountQueriedCallback {

    private RecyclerView recyclerView;
    private TextView groupNameTextView;
    private TextView groupNoticeTextView;
    private TextView groupRemarkTextView;
    private LinearLayout groupNameLayout;
    private LinearLayout groupNoticeLayout;
    private LinearLayout groupRemarkLayout;
    private LinearLayout groupOwnerLayout;
    private SwitchCompat messageRemindSwitch;
    private ImageView imageGroupAvatar;
    private Button groupDismissButton;
    private MessageLoadType messageLoadType;
    private int queryNextFlag;
    private int QUERY_MEMBER_COUNT = 30;
    private static final String IMAGE_URL = "https://storage.zego.im/zim/example/web/assets/%d.jpeg";
    public static final String GROUP_REMARK_ATTR = "GroupMark";
    private GroupMemberGridAdapter memberGridAdapter = new GroupMemberGridAdapter();
    private ZIMGroupFullInfo groupInfo = new ZIMGroupFullInfo();
    private int currentImageIndex = 1;
    public static final int DELETE_MEMBER_RESULT_CODE =100;

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String groupID = getIntent().getStringExtra("groupID");
        groupInfo = new ZIMGroupFullInfo();
        groupInfo.baseInfo = new ZIMGroupInfo();
        groupInfo.baseInfo.groupID = groupID;

        setContentView(R.layout.activity_group_info_detail);
        bindView();
        setGroupEventHandler();
        setGroupMemberInfoClick();

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        queryMemberList();
        SDKManager.sharedInstance().queryGroupInfo(groupID, this);
        SDKManager.sharedInstance().queryGroupMemberCount(groupID, this);

        List<String> keys = new ArrayList();
        keys.add(GROUP_REMARK_ATTR);
        SDKManager.sharedInstance().queryGroupAttributes(keys, groupID, this);
    }

    private void bindView() {
        recyclerView = findViewById(R.id.member_list);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(memberGridAdapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = gridLayoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == memberGridAdapter.getItemCount()) {
                    if (messageLoadType != MessageLoadType.MESSAGE_LOAD_TYPE_LOADING && messageLoadType != MessageLoadType.MESSAGE_LOAD_TYPE_NO_DATA) {
                        queryMemberList();
                    }
                }
            }
        });

        groupNameTextView = findViewById(R.id.group_name);
        groupNoticeTextView = findViewById(R.id.group_notice);
        groupRemarkTextView = findViewById(R.id.group_remark);
        groupNameLayout = findViewById(R.id.group_name_layout);
        groupNoticeLayout = findViewById(R.id.group_notice_layout);
        groupRemarkLayout = findViewById(R.id.group_remark_layout);
        groupOwnerLayout = findViewById(R.id.group_owner_layout);
        groupDismissButton = findViewById(R.id.group_dismiss_button);
        messageRemindSwitch = findViewById(R.id.message_remind_switch);
        imageGroupAvatar = findViewById(R.id.image_group_avatar);

        messageRemindSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ZIMConversationNotificationStatus status = ZIMConversationNotificationStatus.NOTIFY;
                if (isChecked) {
                    status = ZIMConversationNotificationStatus.DO_NOT_DISTURB;
                } else {
                    status = ZIMConversationNotificationStatus.NOTIFY;
                }
                SDKManager.sharedInstance().setConversationNotificationStatus(status, groupInfo.baseInfo.groupID, ZIMConversationType.GROUP, new ZIMConversationNotificationStatusSetCallback() {
                    @Override
                    public void onConversationNotificationStatusSet(String conversationID, ZIMConversationType conversationType, ZIMError errorInfo) {

                        if (errorInfo.code != ZIMErrorCode.SUCCESS) {
                            Toast.makeText(ZIMGroupInfoDetailActivity.this, "Failed to set notification status. error:%s" + errorInfo
                                    .code, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
        imageGroupAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String avatar = String.format(IMAGE_URL, currentImageIndex);
                SDKManager.sharedInstance().updateGroupAvatar(groupInfo.baseInfo.groupID, avatar, new ZIMGroupAvatarUrlUpdatedCallback() {
                    @Override
                    public void onGroupAvatarUrlUpdated(String groupID, String groupAvatarUrl, ZIMError errorInfo) {
                        if (errorInfo.code == ZIMErrorCode.SUCCESS) {
                            setGroupAvatar(groupAvatarUrl);
                        }
                    }
                });
                currentImageIndex++;
                if (currentImageIndex > 5) {
                    currentImageIndex = 1;
                }
            }
        });
        groupNameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZIMGroupNameUpdateActivity.actionStart(ZIMGroupInfoDetailActivity.this, groupInfo.baseInfo.groupID, groupInfo.baseInfo.groupName);
            }
        });

        groupNoticeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZIMGroupNoticeUpdateActivity.actionStart(ZIMGroupInfoDetailActivity.this, groupInfo.baseInfo.groupID, groupInfo.groupNotice);
            }
        });

        groupRemarkLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZIMGroupRemarkUpdateActivity.actionStart(ZIMGroupInfoDetailActivity.this, groupInfo.baseInfo.groupID, groupRemarkTextView.getText().toString());
            }
        });

        groupOwnerLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZIMGroupOwnerTransferActivity.actionStart(ZIMGroupInfoDetailActivity.this, groupInfo.baseInfo.groupID);
            }
        });

    }

    private void queryMemberList() {
        messageLoadType = MessageLoadType.MESSAGE_LOAD_TYPE_LOADING;
        ZIMGroupMemberQueryConfig groupMemberQueryConfig = new ZIMGroupMemberQueryConfig();
        groupMemberQueryConfig.count = QUERY_MEMBER_COUNT;
        groupMemberQueryConfig.nextFlag = queryNextFlag;
        SDKManager.sharedInstance().queryGroupMemberList(groupInfo.baseInfo.groupID, groupMemberQueryConfig, this);
    }

    public void onGroupClearMessage(View view) {
        ZIMMessageDeleteConfig deleteConfig = new ZIMMessageDeleteConfig();
        SDKManager.sharedInstance().deleteAllMessage(groupInfo.baseInfo.groupID, ZIMConversationType.GROUP, deleteConfig, new ZIMMessageDeletedCallback() {
            @Override
            public void onMessageDeleted(String conversationID, ZIMConversationType conversationType, ZIMError errorInfo) {

                if (errorInfo.code != ZIMErrorCode.SUCCESS) {
                    Toast.makeText(ZIMGroupInfoDetailActivity.this, "Failed to clear message error: " + errorInfo.code.name(), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(ZIMGroupInfoDetailActivity.this, "Clear success", Toast.LENGTH_SHORT);
                    Intent intent = new Intent();
                    intent.putExtra("clear_message", true);
                    setResult(DELETE_MEMBER_RESULT_CODE, intent);
                }
            }
        });
    }

    public void onGroupSearch(View view) {
        ZIMGroupSearchFilterActivity.actionStart(this, groupInfo.baseInfo.groupID,
                                                 groupInfo.baseInfo.groupName);
    }
    public void onGroupLeave(View view) {
        SDKManager.sharedInstance().leaveGroup(groupInfo.baseInfo.groupID, new ZIMGroupLeftCallback() {
            @Override
            public void onGroupLeft(String groupID, ZIMError errorInfo) {

                if (errorInfo.code != ZIMErrorCode.SUCCESS) {
                    Toast.makeText(ZIMGroupInfoDetailActivity.this, "Failed to leave group error: " + errorInfo.code.name(), Toast.LENGTH_LONG).show();
                    return;
                }

                Intent intent = new Intent(ZIMGroupInfoDetailActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });
    }

    public void onGroupDismiss(View view) {
        SDKManager.sharedInstance().dismissGroup(groupInfo.baseInfo.groupID, new ZIMGroupDismissedCallback() {
            @Override
            public void onGroupDismissed(String groupID, ZIMError errorInfo) {

                if (errorInfo.code != ZIMErrorCode.SUCCESS) {
                    Toast.makeText(ZIMGroupInfoDetailActivity.this, "Failed to dismiss group error: " + errorInfo.code.name(), Toast.LENGTH_LONG).show();
                    return;
                }

                Intent intent = new Intent(ZIMGroupInfoDetailActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });
    }

    private void setGroupMemberInfoClick() {
        memberGridAdapter.setOnItemClickListener(new GroupMemberGridAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(GroupMemberGridAdapter.GroupMemberUpdateType type) {
                if (type == GroupMemberGridAdapter.GroupMemberUpdateType.GROUP_MEMBER_UPDATE_TYPE_ADD) {
                    ZIMGroupMemberAddActivity.actionStart(ZIMGroupInfoDetailActivity.this, groupInfo.baseInfo.groupID);
                } else if (type == GroupMemberGridAdapter.GroupMemberUpdateType.GROUP_MEMBER_UPDATE_TYPE_Delete) {
                    ZIMGroupMemberDeleteActivity.actionStart(ZIMGroupInfoDetailActivity.this, groupInfo.baseInfo.groupID);
                }
            }

            @Override
            public void onItemInfoClick(ZIMGroupMemberInfo info) {
                SDKManager.sharedInstance().queryGroupMemberInfo(info.userID, groupInfo.baseInfo.groupID, new ZIMGroupMemberInfoQueriedCallback() {
                    @Override
                    public void onGroupMemberInfoQueried(String groupID, ZIMGroupMemberInfo userInfo, ZIMError errorInfo) {
                        Toast.makeText(ZIMGroupInfoDetailActivity.this, "查询成员信息成功，请查看日志", Toast.LENGTH_SHORT).show();
                        AppLogger.getInstance().d("errorCode:%d, errorMsg:%s, userId:%s, userName%s, userAvatar:%s, nickName:%s, memberRole:%d",
                                errorInfo.code.value(), errorInfo.message, userInfo.userID, userInfo.userName
                                , userInfo.memberAvatarUrl, userInfo.memberNickname, userInfo.memberRole);
                    }
                });
            }
        });
    }

    private void setGroupEventHandler() {
        SDKManager.sharedInstance().addGroupNameUpdateCallback(groupNameUpdateCallback);
        SDKManager.sharedInstance().setGroupNoticeUpdatedCallback(new SDKManager.OnGroupNoticeUpdatedCallback() {
            @Override
            public void onGroupNoticeUpdated(ZIM zim, String groupNotice, ZIMGroupOperatedInfo operatedInfo, String groupID) {
                groupInfo.groupNotice = groupNotice;
                groupNoticeTextView.setText(groupNotice);
            }
        });
        SDKManager.sharedInstance().setGroupAttributesUpdatedCallback(new SDKManager.OnGroupAttributesUpdatedCallback() {
            @Override
            public void onGroupAttributesUpdated(ZIM zim, ArrayList<ZIMGroupAttributesUpdateInfo> infos, ZIMGroupOperatedInfo operatedInfo, String groupID) {
                for (ZIMGroupAttributesUpdateInfo updateInfo : infos) {
                    if (updateInfo.action == ZIMGroupAttributesUpdateAction.SET && updateInfo.groupAttributes.containsKey(GROUP_REMARK_ATTR)) {
                        String remark = updateInfo.groupAttributes.get(GROUP_REMARK_ATTR);
                        groupRemarkTextView.setText(remark);
                    }
                }
            }
        });
        SDKManager.sharedInstance().setGroupMemberStateChangedCallback(new SDKManager.OnGroupMemberStateChangedCallback() {
            @Override
            public void onGroupMemberStateChanged(ZIM zim, ArrayList<ZIMGroupMemberInfo> userList, ZIMGroupMemberState state, ZIMGroupMemberEvent event, ZIMGroupOperatedInfo operatedInfo, String groupID) {
                for (ZIMGroupMemberInfo groupMemberInfo : userList) {
                    if (state == ZIMGroupMemberState.ENTER) {
                        memberGridAdapter.addOrUpdate(groupMemberInfo);
                    } else {
                        memberGridAdapter.delete(groupMemberInfo);
                    }
                }
                memberGridAdapter.notifyDataSetChanged();
            }
        });
        SDKManager.sharedInstance().setGroupMemberInfoUpdatedCallback(new SDKManager.OnGroupMemberInfoUpdatedCallback() {
            @Override
            public void onGroupMemberInfoUpdated(ZIM zim, ArrayList<ZIMGroupMemberInfo> userList, ZIMGroupOperatedInfo operatedInfo, String groupID) {
                updateGroupInfo(userList);
            }
        });
    }

    private SDKManager.OnGroupNameUpdateCallback groupNameUpdateCallback = new SDKManager.OnGroupNameUpdateCallback() {
        @Override
        public void onGroupNameUpdated(ZIM zim, String groupName, ZIMGroupOperatedInfo operatedInfo, String groupID) {
            groupInfo.baseInfo.groupName = groupName;
            groupNameTextView.setText(groupName);
        }
    };

    @Override
    public void onGroupAttributesQueried(String groupID, HashMap<String, String> groupAttributes, ZIMError errorInfo) {
        String remark = groupAttributes.get(GROUP_REMARK_ATTR);
        if (remark != null) {
            groupRemarkTextView.setText(remark);
        }
    }


    @Override
    public void onGroupMemberListQueried(String groupID, ArrayList<ZIMGroupMemberInfo> userList, int nextFlag, ZIMError errorInfo) {

        updateGroupInfo(userList);
        queryNextFlag = nextFlag;
        if (nextFlag == 0) {
            messageLoadType = MessageLoadType.MESSAGE_LOAD_TYPE_NO_DATA;
        } else {
            messageLoadType = MessageLoadType.MESSAGE_LOAD_TYPE_LOAD_COMPLETE;
        }
    }

    @Override
    public void onGroupInfoQueried(ZIMGroupFullInfo groupInfo, ZIMError errorInfo) {
        if (errorInfo.code != ZIMErrorCode.SUCCESS) {
            Toast.makeText(this, "Failed to query group info error: " + errorInfo.code.name(), Toast.LENGTH_LONG).show();
            return;
        }
        this.groupInfo = groupInfo;

        if (groupInfo.baseInfo.groupName != null) {
            groupNameTextView.setText(groupInfo.baseInfo.groupName);
        }

        if (groupInfo.groupNotice != null) {
            groupNoticeTextView.setText(groupInfo.groupNotice);
        }

        if (groupInfo.baseInfo.groupAvatarUrl != null) {
            setGroupAvatar(groupInfo.baseInfo.groupAvatarUrl);
        }

        messageRemindSwitch.setChecked(groupInfo.notificationStatus.value() == ZIMGroupMessageNotificationStatus.DISTURB.value());

    }

    private void setGroupAvatar(String avatar) {
        AppLogger.getInstance().d("setGroupAvatar:%s", avatar);
        if (TextUtils.isEmpty(avatar)) {
            return;
        }
        GlideUtils.loadUrl(imageGroupAvatar, avatar);
    }

    @SuppressLint("NotifyDataSetChanged")
    private void updateGroupInfo(List<ZIMGroupMemberInfo> userList) {
        GroupRoleType roleType = GroupRoleType.GROUP_ROLE_TYPE_MEMBER;
        for (ZIMGroupMemberInfo info : userList) {
            if (info.userID.equals(SDKManager.sharedInstance().zimUserInfo.userID) && info.memberRole == GroupRoleType.GROUP_ROLE_TYPE_OWNER.value) {
                roleType = GroupRoleType.GROUP_ROLE_TYPE_OWNER;
            }
            memberGridAdapter.addOrUpdate(info);
        }
        memberGridAdapter.setGroupRole(roleType);
        memberGridAdapter.notifyDataSetChanged();
        if (roleType == GroupRoleType.GROUP_ROLE_TYPE_OWNER) {
            groupOwnerLayout.setVisibility(View.VISIBLE);
            groupDismissButton.setVisibility(View.VISIBLE);
        } else {
            groupOwnerLayout.setVisibility(View.GONE);
            groupDismissButton.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDKManager.sharedInstance().removeGroupNameUpdateCallback(groupNameUpdateCallback);
    }


    @Override
    public void onGroupMemberCountQueried(String groupID, int count, ZIMError errorInfo) {

    }
}
